package com.tzpay.tzpay.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tzpay.tzpay.R;
import com.tzpay.tzpay.bean.FunctionInfoWrapper;
import com.tzpay.tzpay.common.ConstValue;
import com.tzpay.tzpay.ui.activity.WebActivity;
import com.tzpay.tzpay.view.AutoScrollViewPager;
import com.viewpagerindicator.CirclePageIndicator;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by chenfeiyue on 16/4/7.
 */
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final static int TYPE_FUNC = 1;
    private final static int TYPE_BANNER = TYPE_FUNC + 1;

    private ArrayList<FunctionInfoWrapper.ItemsEntity> infos;
    private Context context;

    public void setOnResume(boolean onResume) {
        if (changes != null && changes.size() > 0) {
            for (FragmentOnStateChange change : changes) {
                change.onStateChange(onResume);
            }
        }
    }

    public HomeAdapter(Context context, ArrayList<FunctionInfoWrapper.ItemsEntity> infos) {
        this.infos = infos;
        this.context = context;
    }

    public void addData(ArrayList<FunctionInfoWrapper.ItemsEntity> infos) {
        this.infos.addAll(infos);
        notifyDataSetChanged();
    }

    public void clearData() {
        this.infos.clear();
        if (changes != null) {
            changes.clear();
        }
        notifyDataSetChanged();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        switch (viewType) {
            case TYPE_FUNC:
                return new MyViewHolder(LayoutInflater.from(
                        context).inflate(R.layout.item_home, parent,
                        false));
            case TYPE_BANNER:
                return new MyBannerViewHolder(LayoutInflater.from(
                        context).inflate(R.layout.main_banner_layout, parent,
                        false));
        }
        return new MyViewHolder(LayoutInflater.from(
                context).inflate(R.layout.item_home, parent,
                false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        final FunctionInfoWrapper.ItemsEntity info = infos.get(position);

        if (holder instanceof MyViewHolder) {
            fillDataFunc((MyViewHolder) holder, info);
        } else if (holder instanceof MyBannerViewHolder) {
            fillDataBanner((MyBannerViewHolder) holder, info);
        }
    }


    private void fillDataFunc(MyViewHolder holder, final FunctionInfoWrapper.ItemsEntity info) {
        Glide.with(context)
                .load(info.getImage())
                .fitCenter()
                .into(holder.item_image);
        holder.item_text.setText(info.getFuncName());
        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWebActivity(context, info.getFuncName(), info.getClickUrl());
            }
        });
    }

    private void fillDataBanner(MyBannerViewHolder holder, FunctionInfoWrapper.ItemsEntity info) {

        ArrayList<FunctionInfoWrapper.ItemsEntity.BannersEntity> banners = info.getBanners();
        MyBannerViewPagrAdapter pagerAdapter = new MyBannerViewPagrAdapter(context, banners);

        // viewpager点击事件
        pagerAdapter.setOnBannerClickListener(new MyBannerViewPagrAdapter.OnBannerClickListener() {

            @Override
            public void onBannerClick(FunctionInfoWrapper.ItemsEntity.BannersEntity banner) {
                startWebActivity(context, banner.getFuncName(), banner.getClickUrl());
            }
        });

        holder.viewpager.setAdapter(pagerAdapter);
        holder.viewpager.setInterval(ConstValue.INTERVAL);
        holder.indicator.setViewPager(holder.viewpager);

        // 图片数量小于1张时，隐藏小圆点
        holder.indicator.setVisibility(banners.size() <= 1 ? View.GONE : View.VISIBLE);

        if (banners.size() <= 1) {
            holder.viewpager.stopAutoScroll();
        } else {
            holder.viewpager.startAutoScroll();
        }
        holder.viewpager.setOffscreenPageLimit(banners.size());
        addToOnStateChanges(holder);
    }


    @Override
    public int getItemViewType(int position) {

        final FunctionInfoWrapper.ItemsEntity info = infos.get(position);
        if (info == null) {
            return TYPE_FUNC;
        }
        List<FunctionInfoWrapper.ItemsEntity.BannersEntity> banners = info.getBanners();

        if (banners != null && banners.size() > 0)
            return TYPE_BANNER;
        return TYPE_FUNC;
    }

    public int getSpanSizeLookup(int position) {
        int type = getItemViewType(position);
        switch (type) {
            case TYPE_FUNC:
                return 1;
            case TYPE_BANNER:
                return ConstValue.COLUMN;
            default:
                return 1;
        }
    }

    @Override
    public int getItemCount() {
        return infos.size();
    }


    class MyViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.item_layout)
        View view;
        @Bind(R.id.item_image)
        ImageView item_image;
        @Bind(R.id.item_text)
        TextView item_text;

        public MyViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    class MyBannerViewHolder extends RecyclerView.ViewHolder implements FragmentOnStateChange {

        @Bind(R.id.viewpager)
        AutoScrollViewPager viewpager;
        @Bind(R.id.indicator)
        CirclePageIndicator indicator;

        public MyBannerViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        @Override
        public void onStateChange(boolean b) {
            if (viewpager != null)
                if (b)
                    viewpager.startAutoScroll();
                else
                    viewpager.stopAutoScroll();
        }
    }

    /**
     * 注册点击事件的web方法
     */
    private void startWebActivity(Context context, String title, String link) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("webURL", link);
        context.startActivity(intent);
    }

    private interface FragmentOnStateChange {
        void onStateChange(boolean b);
    }

    private ArrayList<FragmentOnStateChange> changes;

    private void addToOnStateChanges(FragmentOnStateChange change) {
        if (changes == null) {
            changes = new ArrayList<>();
        }
        if (!changes.contains(change)) {
            changes.add(change);
        }
    }

    private boolean removeFromStateChanges(FragmentOnStateChange change) {
        if (changes == null) {
            return false;
        }
        return changes.remove(change);
    }
}